<?php

class Users_IndexController extends Zend_Controller_Action {

    public function init() {
        
    }

    public function indexAction() {
        
    }

    public function loginAction() {
        if ($this->isLogedIn()) {
            $this->_redirect('/home');
        }
        $form = new Users_Form_Login();
        $this->view->form = $form;
        $formErrors = array();
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $loginEmail = $values['email'];
                $loginPassword = md5($values['password']);
                //checking for email existance in database
                $emailValidator = new Zend_Validate_Db_RecordExists(array('table' => 'users', 'field' => 'email'));
                if ($emailValidator->isValid($loginEmail)) {
                    //check email, verified or not...
                    $db = new Users_Model_Users();
                    $user = $db->getUserByEmail($loginEmail);
                    if ($user[0]['close'] == true) {
                        array_push($formErrors, 'Your Account is closed.');
                    } else {
                        if ($user[0]['password'] != $loginPassword) {
                            array_push($formErrors, 'Invalid Password');
                        } else {//email and password are valid
                            $authAdapter = $this->getAuthAction();
                            $authAdapter->setIdentity($loginEmail)
                                    ->setCredential($loginPassword);
                            $auth = Zend_Auth::getInstance();
                            $result = $auth->authenticate($authAdapter);
                            if ($result->isValid()) {
                                $identity = $authAdapter->getResultRowObject();
                                $authStorage = $auth->getStorage();
                                $authStorage->write($identity);
                                $this->_redirect('/home');
                            }
                        }
                    }
                } else {//email not exist in database
                    array_push($formErrors, 'Email not exists.');
                }
                if (sizeof($formErrors) > 0) {
                    $this->view->formErrors = $formErrors;
                }
            }
        }
    }

    public function registerAction() {
        if ($this->isLogedIn()) {
            $this->_redirect('/home');
        }
        $form = new Users_Form_Signup();
        $this->view->form = $form;

        $formErrors = array();
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                //validating email...
                $emailValidator = new Zend_Validate_Db_RecordExists(array('table' => 'users', 'field' => 'email'));
                $email = $values['email'];
                if ($emailValidator->isValid($email)) {
                    array_push($formErrors, 'Email Already Exists.');
                } else {
                    //Validating password...
                    if ($values['password1'] != $values['password2']) {
                        array_push($formErrors, "Password not matched.");
                    } else {
//                        //create new user
                        $password = md5($values['password1']);
                        $db = new Users_Model_Users();
                        $dbData = array(
                            'email' => $email,
                            'password' => $password,
                            'user_type' => 'user',
                            'reg_date' => date('Y-m-d', date('U'))
                        );
                        $db->addNewUser($dbData);
                        $this->_redirect('/user/register/success');
                    }
                }
                if (sizeof($formErrors) > 0) {
                    $this->view->formErrors = $formErrors;
                }
            }
        }
    }

    public function registersuccessAction() {
        // action body
    }

    public function getAuthAction() {
        $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
        $authAdapter->setTableName('users')
                ->setIdentityColumn('email')
                ->setCredentialColumn('password');
        return $authAdapter;
    }

    public function logoutAction() {
        if ($this->isLogedIn()) {
            Zend_Auth::getInstance()->clearIdentity();
            $this->_redirect('/user/login');
        }
    }

    public function isLogedIn() {
        if (Zend_Auth::getInstance()->hasIdentity()) {
            return true;
        } else {
            return false;
        }
    }

}

